package h0906;

import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * @author 不知名帅哥
 * @version 1.0
 * @description 合并k个有序链表
 * @date 2024/9/6 22:23
 */
public class MergeKSortedList {
    public static void main(String[] args) {

    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode mergeKLists(ListNode[] lists) {
        ListNode res = lists[0];
        for (int i = 1; i < lists.length; i++) {
            res=mergeTwo(res,lists[i]);
        }
        return res;
    }

    private static ListNode mergeTwo(ListNode list1,ListNode list2){
        ListNode dummy=new ListNode();
        ListNode preHead=dummy;

        while (list1!=null&&list2!=null){
            if (list1.val<=list2.val){
                preHead.next=list1;
                list1=list1.next;
            }else {
                preHead.next=list2;
                list2=list2.next;
            }
            preHead=preHead.next;
        }
        if (list1!=null){
            preHead.next=list1;
        }
        if (list2!=null){
            preHead.next=list2;
        }
        return dummy.next;
    }
    public ListNode mergeKLists2(ListNode[] lists) {
        if (lists==null||lists.length==0) return null;
        PriorityQueue<ListNode> queue = new PriorityQueue<>(Comparator.comparingInt(o -> o.val));
        ListNode dummy = new ListNode();
        ListNode prehead=dummy;
        for (int i = 0; i < lists.length; i++) {
            if (lists[i]!=null){
                queue.offer(lists[i]);
            }
        }
        while (!queue.isEmpty()){
            ListNode poll = queue.poll();
            prehead.next= poll;
            prehead=prehead.next;
            if (poll.next!=null){
                queue.offer(poll.next);
            }
        }
        return dummy.next;
    }
}
